package com.kuwou.workobject.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.kuwou.workobject.Utils.SingerListUtil;
import com.kuwou.workobject.commonality.ServiceDelegate;
import com.kuwou.workobject.mapper.ChannelMapper;
import com.kuwou.workobject.mapper.SingerListMapper;
import com.kuwou.workobject.pojo.entity.SingerBasicInfo;
import com.kuwou.workobject.pojo.entity.SingerList;
import com.kuwou.workobject.pojo.vo.SingerTopThreeVo;
import com.kuwou.workobject.service.SingerListService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class SingerListServiceImpl extends ServiceImpl<SingerListMapper, SingerList> implements SingerListService{

    private final SingerListMapper singerListMapper;

    @Override
    public void truncateTable() {
        singerListMapper.truncateTable();
    }

    @Override
    public List<SingerTopThreeVo> getSingerTopThree() {
        // 每次查询的条数（可根据实际情况调整，建议500-1000条/批）
        int pageSize = 1000;
        // 起始页码
        int pageNum = 1;
        // 总记录数
        long total = 0;
        List<SingerTopThreeVo> topThree = new ArrayList<>();
        Map<Integer,List<Object>> fansNumRecords= new HashMap<>();
        do {
            //存储singerId
            List<Integer> singerIds = new ArrayList<>();
            // 执行分页查询
            IPage<SingerList> page = SingerListUtil.getSingerList(pageNum, pageSize);
            // 获取当前页数据
            List<SingerList> currentPageData = page.getRecords();
            currentPageData.forEach(singerList -> {
                singerIds.add(singerList.getId());
            });
            List<SingerBasicInfo> singerBasicInfos = Db.listByIds(singerIds, SingerBasicInfo.class);
            Map<Integer,List<Object>> fansMap = new HashMap<>();
            for (int i = 0; i < singerBasicInfos.size(); i++) {
                Integer singerId = singerBasicInfos.get(i).getSingerId();
                String fansNum = singerBasicInfos.get(i).getFansNum();
                String singerName = currentPageData.get(i).getSingerName();
                if (fansNum.contains("W")){
                    double v = Double.parseDouble(fansNum.replace("W", "")) * 10000;
                    fansMap.put(singerId,List.of(v,singerName));
                }
            }

            // 对Map按value排序（从大到小），取前10，结果仍为Map
            Map<Integer, List<Object>> sorted = fansMap.entrySet()
                    .stream()
                    .sorted((entry1, entry2) -> {
                        // 假设 List<Object> 的第一个元素是数字（如粉丝数）
                        Double num1 = (Double) entry1.getValue().get(0);
                        Double num2 = (Double) entry2.getValue().get(0);
                        return Double.compare(num2.doubleValue(), num1.doubleValue());
                    })
                    // 取前10
                    .limit(10)
                    // 收集为LinkedHashMap（保留排序后的顺序）
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,    // 键：singerId
                            Map.Entry::getValue,  // 值：粉丝数
                            (e1, e2) -> e1,       // 若有重复键，保留第一个（根据实际情况处理）
                            LinkedHashMap::new    // 使用LinkedHashMap保持插入顺序（即排序后的顺序）
                    ));
            Iterator<Map.Entry<Integer, List<Object>>> iterator = sorted.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<Integer, List<Object>> entry = iterator.next();
                fansNumRecords.put(entry.getKey(), entry.getValue());
            }

            fansMap.clear();
            // 记录总条数（首次查询时获取）
            if (pageNum == 1) {
                total = page.getTotal();
            }

            // 页码递增
            pageNum++;

            // 当当前页数据量小于每页大小，说明已查询完所有数据
        } while ((pageNum - 1) * pageSize < total);

        //排序
        Map<Integer, List<Object>> topThreeFansNum =
                fansNumRecords.entrySet()
                        .stream()
                        .sorted((entry1, entry2) -> {
                            // 假设 List<Object> 的第一个元素是数字（如粉丝数）
                            Double num1 = (Double) entry1.getValue().get(0);
                            Double num2 = (Double) entry2.getValue().get(0);
                            return Double.compare(num2.doubleValue(), num1.doubleValue());
                        })
                        .limit(3)
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                Map.Entry::getValue,
                                (e1, e2) -> e1,       // 若有重复键，保留第一个（根据实际情况处理）
                                LinkedHashMap::new
                        ));
        List<Integer> singerIds = new ArrayList<>();
        topThreeFansNum.forEach((singerId, fansNum) -> {
            singerIds.add(singerId);
        });

        LambdaQueryWrapper<SingerBasicInfo> queryWrapper =
                new LambdaQueryWrapper<SingerBasicInfo>()
                        .setEntityClass(SingerBasicInfo.class)
                        .in(SingerBasicInfo::getSingerId, singerIds);

        List<SingerBasicInfo> infos = Db.list(queryWrapper);
        for (int i = 0; i < infos.size(); i++) {
            Double fansNum = (Double) topThreeFansNum.get(infos.get(i).getId()).get(0);

            topThree.add(new SingerTopThreeVo(
                    infos.get(i).getId(),
                    (String) topThreeFansNum.get(infos.get(i).getId()).get(1),
                    infos.get(i).getPicUrl(),fansNum.intValue()

            ));
        }
        return topThree;
    }

    @Override
    public List<String> getSingerList(int pageNum,int pageSize) {
        IPage<SingerList> singerList = SingerListUtil.getSingerList(pageNum, pageSize);
        List<SingerList> records = singerList.getRecords();
        List<String> singerNames = new ArrayList<>();
        records.forEach(singer -> {
            singerNames.add(singer.getSingerName());
        });

        return singerNames;
    }
}
